package main

import (
	"fmt"
	"strings"
	"time"
)

//每一个源文件都可以包含一个init函数，该函数在main之前执行
func init() {
	fmt.Println("init before main func")
}

//执行顺序：1全局变量 2 init 3 main
var age = getAge()

func getAge() int {
	fmt.Println("gloal value set")
	return 12
}

func showInfo() {
	defer fmt.Println("defer called")
	fmt.Println("show")
}

func testError() {
	defer func() {
		//获取错误
		error := recover()
		if error != nil {
			fmt.Println(error)
		}
	}()
	num1 := 5
	num2 := 0
	if num2 == 0 {
		//引发自定义错误
		panic("div 0")
	}
	fmt.Println(num1 / num2)
}

func main() {
	fmt.Println("main execing...")

	//1 匿名函数
	f := func() int {
		return 12
	}()

	fmt.Println("f is", f)

	//2 defer
	showInfo()

	//3 字符串函数
	str := "中"
	//len字节长度
	fmt.Println("str len is：", len(str))
	fmt.Println(strings.Contains("hello world", "he"))
	fmt.Println(strings.Count("she is shoe", "sh"))
	//不区分大小写比较
	fmt.Println(strings.EqualFold("hello", "HELlo"))
	fmt.Println(strings.Index("hello world", "wo"))
	//nellnh
	fmt.Println(strings.Replace("hellhh", "h", "n", 2))
	strArr := strings.Split("hello,world", ",")
	for _, val := range strArr {
		fmt.Println(val)
	}
	fmt.Println(strings.ToLower("HELLO"))
	fmt.Println(strings.Trim(",,,,j,,,,", ","))

	//4 日期函数
	now := time.Now()
	//2006-01-02 15:04:05
	fmt.Println(now.Format("2006-01-02 15:04:05"))
	time.Sleep(time.Nanosecond)

	//5 内置函数
	num := new(int) //*int
	*num = 100
	fmt.Printf("num的类型%T,num值%v,num地址%v,指向的地址%v\n", num, num, &num, *num)

	//6 错误
	testError()
}
